﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CardLogistics.Web.Components;
using CardLogistics.Model.CardMaking;
using System.Data;


namespace CardLogistics.Web.MainPage.CardMaking.CardDemand
{
    public partial class AddEdit : BasePage
    {
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardDemandData DAL = new CardLogistics.DAL.CardMaking.CardMaking_CardDemandData();
        private static readonly CardLogistics.DAL.CardMaking.CardMaking_CardDemandDetailData DDAL = new CardLogistics.DAL.CardMaking.CardMaking_CardDemandDetailData();
        string demandId = "";//卡片需求编号Id
        protected Dictionary<string, string> CardTypeList = null;
        public string TitleName
        {
            get;
            set;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                APPLICADATE.Value = DateTime.Now.ToString("yyyy-MM-dd");//申领日期
                APPLICANT.Value = LoggedUser.USERFULLNAME;//申请人默认为当前登录用户
                CardTypeList = GetCardTypeList();
                InitControl();
            }
        }

        #region 获取卡类型
        private Dictionary<string, string> GetCardTypeList()
        {
            // var BranchArray = CardTypeList.ToDictionary(k => k.ID, k => k.Name);可以把数据库查出来的list转换成Dictionary
            Dictionary<string, string> cardTypeList = new Dictionary<string, string>();
            DataTable dt = CardLogistics.DAL.DbHelperSQL.GetQueryResult("select id,cardtypename from basic_cardtype where STATUS=0 and ISDELETE=0 and FathercardtypeId !='0'");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string id = dt.Rows[i]["id"].ToString();
                string cardtypename = dt.Rows[i]["cardtypename"].ToString();
                cardTypeList.Add(id, cardtypename);
            }
            return cardTypeList;
        }
        #endregion

        #region 编辑时绑定值
        /// <summary>
        /// 编辑时绑定值
        /// </summary>
        public void InitControl()
        {
            TitleName = GetStatusInfo(0, "卡片需求单");
            if (IsEdit)
            {
                string _key = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(_key))
                {
                    CardMaking_CardDemand pData = DAL.GetModel(_key);
                    SetWebControls(this.Page, pData);
                    DataTable dt = DDAL.GetInfoByDemandId(pData.ID);
                    string detName = "";
                    string detId = "";
                    if (dt != null && dt.Rows.Count > 0)
                    {
                        foreach (DataRow dr in dt.Rows)
                        {
                            detName += dr["cardtypename"].ToString() + "[" + dr["CARDNUMBER"].ToString() + "];";
                            detId += dr["CARDTYPE"].ToString() + "|" + dr["CARDNUMBER"].ToString() + ";";
                        }
                        //PConNo.Value = detName.TrimEnd(';') + "  总数量:" + Convert.ToInt32(dt.Compute("sum(CARDNUMBER)", ""));//赠品数量;
                        hf_ConId.Value = detId.TrimEnd(';');
                    }
                    btn_Add.Visible = btn_Submit.Visible = false;
                    if (pData.ISSUBMIT == 0 || pData.ISSUBMIT == 3)//状态为 0(未提交) 或 3(驳回)时才可以进行编辑操作
                    {
                        btn_Add.Visible = btn_Submit.Visible = true;
                    }
                    WriteJavaScript("document.getElementById(\"REMARKS\").value = \"adafdasfd\";", false);
                    TitleName = GetStatusInfo(int.Parse(pData.ISSUBMIT.ToString()), "卡片需求单");
                }
            }
            else
            {
                DEMANDNO.Value = GetBillNumber("卡片需求单");
            }

        }
        #endregion

        /// <summary>
        /// 保存按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                ClientScript.RegisterStartupScript(this.GetType(), "message", " <script language='javascript' >if(Confirm('确认码?')); </script>");  

                string result = EncapsulationModel(0);
                if (result.Split(',')[0] == "ok")
                {
                    InsertLog("保存卡片需求单信息,需求单号:" + DEMANDNO.Value);
                    ReturnListInfo();

                }
                else
                {
                    ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }
        /// <summary>
        /// 保存并提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                string result = EncapsulationModel(1);
                if (result.Split(',')[0] == "ok")
                {
                    InsertAppInfo(4, result.Split(',')[1]);
                    InsertLog("保存并提交卡片需求单信息,需求单号:" + DEMANDNO.Value);
                    ReturnListInfo();
                }
                else
                {
                    ShowMessageBox("操作失败请重新操作！" + result.Split(',')[1]);
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox("系统异常:" + ex.ToString());
            }
        }

        /// <summary>
        /// 需求信息
        /// </summary>
        /// <param name="issubmit">是否提交</param>
        /// <returns></returns>
        private string EncapsulationModel(int issubmit)
        {
            CardMaking_CardDemand model = new CardMaking_CardDemand();
            model = GetWebControls<CardMaking_CardDemand>(this.Page);
            model.LASTUPDATEUSER = LoggedUser.ID;
            model.LASTUPDATEDATE = DateTime.Now;
            model.ISSUBMIT = issubmit;
            model.Details = hf_ConId.Value + ";";
            demandId = model.ID;//获取卡片需求单ID
            string result = string.Empty;
            if (IsEdit)
            {
                model.ID = Request.QueryString["id"];
                result = DAL.Update(model);
            }
            else
            {
                result = DAL.Add(model);
                if (result.Split(',')[0] == "ok")
                {
                    ChgBillNumber("卡片需求单");
                }

            }
            return result;
        }
    }
}